package com.example.woke1;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.silent.handle.CharacterParser;
import com.silent.handle.PinyinComparator;
import com.silent.handle.SideBar;
import com.silent.handle.SideBar.OnTouchingLetterChangedListener;
import com.woke.data.Data_myfriendb;
import com.woke.method.MyApp;
import com.zhongcai.online.R;

import java.util.ArrayList;
import java.util.Collections;

public class PhonefriendActivity extends Activity implements OnItemClickListener {

	private ListView mListView;
	/** ��ϵ����� **/
	private ArrayList<String> mContactsName = new ArrayList<String>();

	/** ��ϵ�˺��� **/
	private ArrayList<String> mContactsNumber = new ArrayList<String>();

	/** ��ϵ��ͷ�� **/
//	private ArrayList<Bitmap> mContactsPhonto = new ArrayList<Bitmap>();
	
	private static final String[] PHONES_PROJECTION = new String[] {  
	       Phone.DISPLAY_NAME, Phone.NUMBER, Phone.PHOTO_ID,Phone.CONTACT_ID }; 

	/**��ϵ����ʾ���**/  
    private static final int PHONES_DISPLAY_NAME_INDEX = 0;  
      
    /**�绰����**/  
    private static final int PHONES_NUMBER_INDEX = 1;  
      
    /**ͷ��ID**/  
    private static final int PHONES_PHOTO_ID_INDEX = 2;  
     
    /**��ϵ�˵�ID**/  
    private static final int PHONES_CONTACT_ID_INDEX = 3;
	private String stringExtra ;//�ж��Ƿ���ʾ���� 
	private Intent intent;
	private MyApp application;
	
	/**
	 * ����ת����ƴ������
	 */
	private CharacterParser		characterParser;
	/**
	 * ���ƴ��������ListView����������
	 */
	private PinyinComparator	pinyinComparator;
	
	private ArrayList<Data_myfriendb> datalist = new ArrayList<Data_myfriendb>();
	private SideBar	sideBar;
	private EditText mEcarno;
	private Phoneadater adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_phonefriend);
		
		application = (MyApp) getApplication();
		intent = getIntent();
		stringExtra  = ""+intent.getStringExtra("from");
		intview();
		
	}

	private void intview() {
		findViewById(R.id.avphonef_image_back).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		sideBar = (SideBar) findViewById(R.id.sidrbar1);
		// �����Ҳഥ������
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				// ����ĸ�״γ��ֵ�λ��
				int position = adapter.getPositionForSection(s.charAt(0));
				if(position != -1) {
					mListView.setSelection(position);
				}
			}
		});
		mEcarno = (EditText) findViewById(R.id.avborrowf_edit_search1);
		mEcarno.addTextChangedListener(watcher);
		// ʵ����תƴ����
		characterParser = CharacterParser.getInstance();
		pinyinComparator = new PinyinComparator();
		mListView = (ListView) findViewById(R.id.avphonef_listview);
		mListView.setOnItemClickListener(this);
		getPhoneContacts();
		
	}
	
	private TextWatcher watcher = new TextWatcher() {
	    @Override
	    public void onTextChanged(CharSequence s, int start, int before, int count) {
	    }
	    @Override
	    public void beforeTextChanged(CharSequence s, int start, int count,
	            int after) {
	    }
	    
	    @Override
	    public void afterTextChanged(Editable s) {
	    	String trim = ""+mEcarno.getText().toString().trim();
	    	if(trim.equals("")){
//	    		mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightgray));
	    	}else{
	    		int length = trim.length();
//	    		Log.e("length", ""+length);
	    		for (int i = 0; i < datalist.size(); i++) {
	    			if(datalist.get(i).head.length() >= length){
					if(datalist.get(i).head.substring(0, length).endsWith(trim)){
						mListView.setSelection(i);
						return;
						}
	    			}
				}
//	    		mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightred));
	    	}
	    }
	};
	
	private void getPhoneContacts() {
		ContentResolver resolver = getContentResolver();

		// ��ȡ�ֻ���ϵ��
		Cursor phoneCursor = resolver.query(Phone.CONTENT_URI,
				PHONES_PROJECTION, null, null, null);

		if (phoneCursor != null) {
			
			while (phoneCursor.moveToNext()) {
				String phoneNumber ="";
				// �õ��ֻ����
				 phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
				if(phoneNumber.substring(0, 3).equals("+86")){
					phoneNumber = phoneNumber.substring(3, phoneNumber.length()).replace(" ", "");
				}
				// ���ֻ����Ϊ�յĻ���Ϊ���ֶ� ���ǰѭ��
				if (TextUtils.isEmpty(phoneNumber))
					continue;

				// �õ���ϵ�����
				String contactName = phoneCursor
						.getString(PHONES_DISPLAY_NAME_INDEX);

				// �õ���ϵ��ID
				Long contactid = phoneCursor.getLong(PHONES_CONTACT_ID_INDEX);

				// �õ���ϵ��ͷ��ID
				Long photoid = phoneCursor.getLong(PHONES_PHOTO_ID_INDEX);

				mContactsName.add(contactName);
				mContactsNumber.add(phoneNumber);
				
				//���� �ֻ� ���� ���� ����ĸ
				String shouzimu = "";
				// ����ת����ƴ��
				String pinyin = characterParser.getSelling(contactName);
				String sortString = pinyin.substring(0, 1).toUpperCase();
				// ������ʽ���ж�����ĸ�Ƿ���Ӣ����ĸ
				if(sortString.matches("[A-Z]")) {
					shouzimu = sortString.toUpperCase();
				} else {
					shouzimu = "#";
				}
				
				Data_myfriendb list = new Data_myfriendb(contactName, phoneNumber, "",0,shouzimu);
				datalist.add(list);
			}
			phoneCursor.close();
//			 ���a-z��������Դ���
			if(datalist.size() > 0){
				Collections.sort(datalist, pinyinComparator);
				adapter = new Phoneadater();
				mListView.setAdapter(adapter);
				String string = mContactsNumber.toString();
				String substring = string.substring(1, string.length() - 1);
//				sendphonelist(substring);
			}
			
		}
	}
	
	
	class Phoneadater extends BaseAdapter{

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mContactsName.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}
		
		public class Holder{
			TextView username,catalog1;
			ImageView yaoqing;
		}
		
		/**
		 * ���ListView�ĵ�ǰλ�û�ȡ���������ĸ��Char asciiֵ
		 */
		public int getSectionForPosition(int position) {
			return datalist.get(position).shouzimu.charAt(0);
		}

		/**
		 * ��ݷ��������ĸ��Char asciiֵ��ȡ���һ�γ��ָ�����ĸ��λ��
		 */
		public int getPositionForSection(int section) {
			for (int i = 0; i < getCount(); i++) {
				String sortStr = datalist.get(i).shouzimu;
				char firstChar = sortStr.toUpperCase().charAt(0);
				if(firstChar == section) {
					return i;
				}
			}

			return -1;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			Holder holder = null;
			if(convertView == null){
				holder = new Holder();
				convertView = getLayoutInflater().inflate(R.layout.item_phonef_adter, null);
				holder.username = (TextView) convertView.findViewById(R.id.item_phonef_name);
				holder.yaoqing = (ImageView) convertView.findViewById(R.id.item_phonef_yaoqing);
				holder.catalog1 = (TextView) convertView.findViewById(R.id.catalog1);
				convertView.setTag(holder);
			}else{
				 holder = (Holder) convertView.getTag();
			}
			
			if(stringExtra.equals("where") || stringExtra.equals("where1")){
				holder.yaoqing.setVisibility(View.GONE);
			}
			Data_myfriendb data = datalist.get(position);
			// ���position��ȡ���������ĸ��Char asciiֵ
			int section = getSectionForPosition(position);

			// ���ǰλ�õ��ڸ÷�������ĸ��Char��λ�� ������Ϊ�ǵ�һ�γ���
			if(position == getPositionForSection(section)) {
			holder.catalog1.setVisibility(View.VISIBLE);
			holder.catalog1.setText(data.shouzimu);
						} else {
			holder.catalog1.setVisibility(View.GONE);
						}
			holder.username.setText(data.head);
			
			return convertView;
		}
		
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Data_myfriendb data = datalist.get(arg2);
		if(stringExtra.equals("where")){
			Intent intent = new Intent();
			intent.setAction("com.woke.cxtongactivity");
			intent.putExtra("phoneno", data.userid);
			sendBroadcast(intent);
			finish();
			
		}else if(stringExtra.equals("where1")){
			Intent intent = new Intent();
			intent.setAction("com.woke.cxtonglactivity");
			intent.putExtra("phoneno", data.userid);
			sendBroadcast(intent);
			finish();
		}
	}
	
}
